<?php

namespace chuanglan;

use ShidianUtil\Api\Sms\TemplateSmsResponse;
use ShidianUtil\Net\IHttpClient;
use ShidianUtil\Thinkphp\Lib\Logger\RequestLogger;
use ShidianUtil\Thinkphp\Model\LogApiSms;
use ShidianUtil\Utils\ConvertUtil;
use think\facade\Config;
use think\facade\Log;
use Throwable;

/**
 * Class Sms
 * @package chuanglan
 * @url https://www.chuanglan.com/document/6110e57909fd9600010209de/62b3dc1d272e290001af3e75#aVIym
 */
class Sms
{
    /**
     * @var IHttpClient
     */
    private $httpClient;

    /**
     * @param IHttpClient $httpClient
     */
    public function __construct(IHttpClient $httpClient)
    {
        $this->httpClient = $httpClient;
    }

    /**
     * 发送短信
     * @param string $phone
     * @param string $content
     * @param array $var
     * @return TemplateSmsResponse
     */
    public function send(string $phone, string $content, array $var): TemplateSmsResponse
    {

        $response = $this->sendSms($phone, $content, $var);

        $this->insertLog($phone, $var, $content, $response);

        return $response;
    }

    // 发送请求
    private function sendSms(string $phone, string $content, array $var): TemplateSmsResponse
    {

        $uri = 'https://smssh1.253.com/msg/variable/json';

        $config = Config::get('chuanglan', []);

        $params = $phone . ',' . implode(',', $var);

        $post = [];
        $post['account'] = $config['account'] ?? '';
        $post['password'] = $config['password'] ?? '';
        $post['msg'] = $content;
        $post['params'] = $params;
        $post['report'] = 'true';

        $response = $this->httpClient->postJSONFormat($uri, [], [], $post);

        $body = $response->getBody()->__toString();

        if ($response->getStatusCode() != 200) {
            Log::error('chuanglan短信发送接口HTTP状态码异常{code}，响应{body}', ['code' => $response->getStatusCode(), 'body' => $body]);
            return new TemplateSmsResponse($response, false, []);
        }

        $data = [];

        try {
            $data = ConvertUtil::jsonDecode($body);

            $code = $data['code'] ?? null;
            if ($code === 0 || $code === '0') {
                return new TemplateSmsResponse($response, true, $data);
            }

            Log::error('chuanglan短信发送接口响应码错误，响应{body}', ['body' => $body]);
            return new TemplateSmsResponse($response, false, $data);
        } catch (Throwable $throwable) {

            Log::error('chuanglan短信发送接口异常，原因{message}', ['message' => $throwable->getMessage()]);
            return new TemplateSmsResponse($response, false, $data);
        }
    }

    // 插入日志
    private function insertLog($phone, $params, $content, $templateSmsResponse)
    {

        $log_request = RequestLogger::get();
        $log_request_id = $log_request ? $log_request->id : 0;

        $params = [
            'phone' => $phone,
            'params' => $params,
            'template_id' => '',
            'content' => $content,
            'response' => ConvertUtil::jsonEncode($templateSmsResponse->getDecodeContents()),
            'result' => $templateSmsResponse->isSuccess() ? '101' : '102',
            'log_request_id' => $log_request_id,
        ];

        $model = new LogApiSms();

        $model->save($params);
    }
}
